package org.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.Util.JwtUtil;
import org.example.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class TestInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (request.getRequestURI().contains("/login")) {
            return true;
        }

        //判断是否携带token
        String token = request.getHeader("token");
        if (token == null) {
            // 输出为空日志
            log.info("token为空");
            Result error = Result.error("NOT_LOGIN");
            // 通过fastjson将Result对象转换为json字符串
            String json = JSONObject.toJSONString(error);
            response.getWriter().write(json);
            return false;
        }
        log.info("token不为空");
        try {
            jwtUtil.checkToken(token);
        } catch (Exception e) {
            log.info("token验证失败");
            Result error = Result.error("NOT_LOGIN");
            // 通过fastjson将Result对象转换为json字符串
            String json = JSONObject.toJSONString(error);
            response.getWriter().write(json);
            return false;
        }
        log.info("token验证成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
